//@Author: Adrian "yEnS" Mato Gondelle & Ivan Guardado Castro
//@website: www.yensdesign.com
//@email: yensamg@gmail.com
//@license: Feel free to use it, but keep this credits please!
/***************************/

//alert(handleResize());
//document.getElementById("accordion").style.height=

var Flag_Search_Panel_Status="BIO";
var selectedbutton=true;
var bioFilterWindow=false;
var nonbioFilterWindow=false;


$(document).ready(function(){
$(".panel").toggle();
$(".panel_detail").toggle();
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
document.getElementById("hdSearchDetails").value="0";
$('a#markerbutton').toggleClass("down");
document.getElementById("searchresult").style.height  = (document.documentElement.clientHeight-$("#header").height()-$("#toolbarmap").height()-25) + "px";
document.getElementById("searchresult").style.top  = $("#header").height()+$("#toolbarmap").height() + "px";
document.getElementById("panel_detail").style.top  = $("#header").height() + "px";

document.getElementById("divsearchfilter_bio").style.left=((document.documentElement.clientWidth/2)-420) +"px"
document.getElementById("divsearchfilter_nonbio").style.left=((document.documentElement.clientWidth/2)-340) +"px"

$(document).mousemove(function(e){
       if (e.pageX>=(document.documentElement.clientWidth-30) && e.pageX<=(document.documentElement.clientWidth-10) && e.pageY>=35 && e.pageY<=55 && $(".trigger").is(":visible")==false)
       {
           document.getElementById("searchbox").style.cursor='pointer';
           
       }
       else if (e.pageX>=(document.documentElement.clientWidth-50) && e.pageX<=(document.documentElement.clientWidth-30) && e.pageY>=35 && e.pageY<=55 && $(".trigger").is(":visible")==true)
       {
           document.getElementById("searchbox").style.cursor='pointer';

       }
       else
       {
           document.getElementById("searchbox").style.cursor='text';
           
       }
       
   });

   $(document).click(function(e){
       if (e.pageX>=(document.documentElement.clientWidth-30) && e.pageX<=(document.documentElement.clientWidth-10) && e.pageY>=35 && e.pageY<=55 && $(".trigger").is(":visible")==false)
       {
           SearchProcess();

       }
       else if (e.pageX>=(document.documentElement.clientWidth-50) && e.pageX<=(document.documentElement.clientWidth-30) && e.pageY>=35 && e.pageY<=55 && $(".trigger").is(":visible")==true)
       {
           SearchProcess();

       }


   });


	//On Click Event
	$("ul.tabs li").click(function() {

                if(Flag_Search_Panel_Status=="OVERLAY" && $(this).find("a").attr("id")=="btngraph"){
                
//               selectedbutton="";
//               document.getElementById("hdSearchDetails").value="0";
//               $("#panel_detail").hide();
//                    return;
}

		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content


                if($(".panel_detail").is(":visible")==false){

                showhidedetails();
                }
                else if ($(".panel_detail").is(":visible")==true && selectedbutton==$(this).find("a").attr("id"))
                    {
                        if($(".panel_detail").is(":visible")==true){

                                showhidedetails();
                }
                    }

                    if (selectedbutton!=$(this).find("a").attr("id") && $(".panel_detail").is(":visible")==true && $(this).find("a").attr("id")=="btngraph")

                        {
                           loadgraph("");
                        }
                   else if (selectedbutton!=$(this).find("a").attr("id") && $(".panel_detail").is(":visible")==true && $(this).find("a").attr("id")=="btndata")

                        {
                           

                        }     
                   else if (selectedbutton!=$(this).find("a").attr("id") && $(".panel_detail").is(":visible")==true && $(this).find("a").attr("id")=="btncitation")

                        {
                           if (Flag_Search_Panel_Status=="BIO")
                                loadCitation(getBioselection(),"BIO");
                            else if (Flag_Search_Panel_Status=="NONBIO")
                                loadCitation(getNonbioselection(),"NONBIO");
                            else if (Flag_Search_Panel_Status=="OVERLAY")
                                loadCitation(getOverlayselection(),"OVERLAY");
                        }



                    selectedbutton=$(this).find("a").attr("id");

		return false;
	});



$("#searchbox").keypress(function(event) {
        if (event.which == '13') {
            SearchProcess();
        }
                                });

$("#searchbox").blur(function() {
        if ($("#searchbox").val()=="") {
               
        }
                                });


$(".trigger").click(function(){
            $(this).toggleClass("active");
                $(".panel").toggle();
                AdjustPanelSize();
                return false;
	});


$('a#markerbutton').click(function(){
        $(this).toggleClass("down");
        if (document.getElementById("hdShowMarkers").value=="1")
            {
                document.getElementById("hdShowMarkers").value="0";

            }
        else if (document.getElementById("hdShowMarkers").value=="0")
            {
                document.getElementById("hdShowMarkers").value="1";

            }
                loadMarker(map,getBioselection()+"flg_bio_and_nonbio_map_point"+getNonbioselection(),applyFilter());

    });
$.widget( "custom.catcomplete", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
			var self = this,
				currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.category != currentCategory ) {
					ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
					currentCategory = item.category;
				}
				self._renderItem( ul, item );
			});
		}
	});
        $.post("http://"+location.hostname+"/visualization/autocomplete", {}, function(data) {
                var atData=data.split("###");
                var tmp;
                var ArrayData=[];
                for (var a=0; a<=atData.length-2;a++)
                    {
                        tmp=atData[a].split("***");
                        ArrayData[a]={label: tmp[0], category:tmp[1]};
                    }
		$( "#searchbox" ).catcomplete({
			delay: 0,   
			source: ArrayData,
                        select: function(event, ui) {$("#searchbox").val(ui.item.value);SearchProcess();}
		});
        });



searchResearch(getURLParameter( 'RID' ));


});


$(window).resize(function() {
document.getElementById("searchresult").style.height  = (document.documentElement.clientHeight-$("#header").height()-$("#toolbarmap").height()-25) + "px";
document.getElementById("searchresult").style.top  = $("#header").height()+$("#toolbarmap").height() + "px";
document.getElementById("panel_detail").style.top  = $("#header").height()+ "px";

if(((document.documentElement.clientWidth/2)-420)<=200){document.getElementById("divsearchfilter_bio").style.left = "0px";document.getElementById("divsearchfilter_nonbio").style.left="0px"} else {document.getElementById("divsearchfilter_bio").style.left=((document.documentElement.clientWidth/2)-420) +"px";document.getElementById("divsearchfilter_nonbio").style.left=((document.documentElement.clientWidth/2)-340) +"px";}


AdjustPanelSize();

document.getElementById("searchresultdetailtab").style.height  = (document.documentElement.clientHeight*10)/100 + "px";
                              if(document.getElementById("accordion")){document.getElementById("accordion").style.height  = (document.documentElement.clientHeight-60) + "px";}
                              if(document.getElementById("divbiodata")){document.getElementById("divbiodata").style.height  = (document.documentElement.clientHeight-175) + "px";}
                              if(document.getElementById("divnonbiodata")){document.getElementById("divnonbiodata").style.height  = (document.documentElement.clientHeight-175) + "px";}
                              if(document.getElementById("divoverlaydata")){document.getElementById("divoverlaydata").style.height  = (document.documentElement.clientHeight-175) + "px";}

loadgraph("");
        });



function AdjustPanelSize()
{
    if (document.getElementById("hdtrigger").value=="0")
                {document.getElementById("hdtrigger").value=1;
                        document.getElementById("GraphBio_Bar").style.width  = (document.documentElement.clientWidth-357) + "px";
                        document.getElementById("searchresultdetailtab").style.width  = (document.documentElement.clientWidth-415) + "px";
                        document.getElementById("searchresultcitationtab").style.width  = (document.documentElement.clientWidth-357) + "px";
                        
                        document.getElementById("imgtrigger").src='/images/up.png';
                        loadgraph("");
                    }
            else if (document.getElementById("hdtrigger").value=="1")
                {document.getElementById("hdtrigger").value=0;
                    document.getElementById("GraphBio_Bar").style.width  = (document.documentElement.clientWidth-30) + "px";
                        document.getElementById("searchresultdetailtab").style.width  = (document.documentElement.clientWidth-30) + "px";
                        document.getElementById("searchresultcitationtab").style.width  = (document.documentElement.clientWidth-30) + "px";
                        
                        document.getElementById("imgtrigger").src='/images/down.png';
            loadgraph("");
            }

}
function SearchProcess()
{
    if($("#searchbox").val()!="")
                                    {$("#divsearchfilter_bio").hide();
                $(".trigger").show();
                if($(".panel").is(":visible")==false){


                $(".panel").toggle();

                $(".trigger").toggleClass("active");
		}
                var cValue = $("#searchbox").val();
                

                $.post("http://"+location.hostname+"/visualization/search", {search: cValue.replace("'","''") +"flag_search_d_pg_t"+"ALL"}, function(data) {
                                $("#tdsearchresult").html(data);

                                setAccordion();


                              if(document.getElementById("accordion")){document.getElementById("accordion").style.height  = (document.documentElement.clientHeight-60) + "px";}
                              if(document.getElementById("divbiodata")){document.getElementById("divbiodata").style.height  = (document.documentElement.clientHeight-175) + "px";}
                              if(document.getElementById("divnonbiodata")){document.getElementById("divnonbiodata").style.height  = (document.documentElement.clientHeight-175) + "px";}
                              if(document.getElementById("divoverlaydata")){document.getElementById("divoverlaydata").style.height  = (document.documentElement.clientHeight-175) + "px";}
                });

                                    }
}





function setAccordion()
{
if($('#ac1').is(":visible")==true)
{
    Flag_Search_Panel_Status="BIO";
}
else if($('#ac2').is(":visible")==true && $('#ac1').is(":visible")==false)
{
    Flag_Search_Panel_Status="NONBIO";
}
else if($('#ac3').is(":visible")==true && $('#ac1').is(":visible")==false && $('#ac2').is(":visible")==false)
{
    Flag_Search_Panel_Status="OVERLAY";
}

$("#accordion").accordion({collapsible: false,

                    change: function(event, ui) {

                     if (ui.newHeader.text().indexOf("Biological Data:")==0)
                         {
                             Flag_Search_Panel_Status="BIO";
                             searchaction("chkbio",false);
                             showhideFilter(true);
                         }
                    else if (ui.newHeader.text().indexOf("Specific Units:")==0)
                         {
                             Flag_Search_Panel_Status="NONBIO";
                             searchaction("chknonbio",false);
                             showhideFilter(true);
                         }
                    else if (ui.newHeader.text().indexOf("Overlay Data")==0)
                         {
                             Flag_Search_Panel_Status="OVERLAY";
                             searchaction("chkoverlay",false);
                             showhideFilter(true);
                         }
                             
                      }
}
            );
}

function selectall(oid)
{
    var sall=true;
    var objname="";
    if (oid=="selectallbio")
        {sall=true;objname="chkbio";}
    else if (oid=="selectallnonbio")
        {sall=true;objname="chknonbio";}
    else if (oid=="selectalloverlay")
        {sall=true;objname="chkoverlay";}
    else if (oid=="unselectallbio")
        {sall=false;objname="chkbio";}
    else if (oid=="unselectallnonbio")
        {sall=false;objname="chknonbio";}
    else if (oid=="unselectalloverlay")
        {sall=false;objname="chkoverlay";}

    var v=document.getElementsByName(objname);
    for (i=0;i<v.length;i++)
        {
            v[i].checked=sall;
        }


    searchaction(objname,true);

}

function getBioselection()
{
    var v=document.getElementsByName("chkbio");
    var str="";
    
    for (i=0;i<v.length;i++)
        {
            if (v[i].checked)
                {
                    if (str!="")
                    {
                        str=str+","
                    }
                    str=str+v[i].id;
                    
                }
        }
       
        return str;
}
function getNonbioselection()
{
    var v=document.getElementsByName("chknonbio");
    var str="";

    for (i=0;i<v.length;i++)
        {
            if (v[i].checked)
                {
                    if (str!="")
                    {
                        str=str+","
                    }
                    str=str+v[i].id;

                }
        }

        return str;
}
function getOverlayselection()
{
    var v=document.getElementsByName("chkoverlay");
    var str="";

    for (i=0;i<v.length;i++)
        {
            if (v[i].checked)
                {
                    if (str!="")
                    {
                        str=str+","
                    }
                    str=str+v[i].id;

                }
        }

        return str;
}

function searchaction(tg,boolreloadfilter)
{
    
    if (tg=="chkbio")
        {
        var bioselection=getBioselection();
        if (boolreloadfilter==true)setSearchFilter(bioselection,"BIO");
        
        delGraphMarker();
        loadMarker(map,bioselection+"flg_bio_and_nonbio_map_point",applyFilter());
        
        //setOverlayImageWithOpacity(map,"", 70);

        if (bioselection!="")
            {
                graphShowButton(true);
                if($("#panel_detail").is(":visible")==true){
                    if (selectedbutton=="btngraph")
                        reloadgraphfromcluster=true;
                    
                    else if (selectedbutton=="btncitation")
                        loadCitation(getBioselection(),"BIO");
                }

            }
       else
           {
               graphShowButton(false);
               selectedbutton="";
               showhidedetails();
               return;
           }
        
        
        
        }

        else if ( tg=="chknonbio")
        {
        var nonbioselection=getNonbioselection();
      if (boolreloadfilter==true) setSearchFilter(nonbioselection,"NONBIO");
        delGraphMarker();
        loadMarker(map,"flg_bio_and_nonbio_map_point"+nonbioselection,applyFilter());

        
        //setOverlayImageWithOpacity(map,"", 70);
        if (nonbioselection!="")
            {
            graphShowButton(true);
            if($("#panel_detail").is(":visible")==true){
                    if (selectedbutton=="btngraph")
                        loadgraph(nonbioselection);
                    
                    else if (selectedbutton=="btncitation")
                        loadCitation(nonbioselection,"NONBIO");
                }

        }
         else
           {
               graphShowButton(false);
               selectedbutton="";
               showhidedetails();
               return;
           }
        }
        

    

else if (tg=="chkoverlay" )
    {
        var overlayselection=getOverlayselection();
        if (boolreloadfilter==true) setSearchFilter(overlayselection,"OVERLAY");
        
        setOverlayImageWithOpacity(map,overlayselection, 70);
        delGraphMarker();
        //loadMarker(map,"","");

         if (overlayselection!="")
            {
            graphShowButton(true);
            if($("#panel_detail").is(":visible")==true){
                    if (selectedbutton=="btngraph")
                        {//showhidedetails();
                           
                        }
                    
                    else if (selectedbutton=="btncitation")
                        loadCitation(overlayselection,"NONBIO");
                }

            }
         else
           {
               graphShowButton(false);
               selectedbutton="";
               showhidedetails();
               return;
           }

$("#divsearchfilter_bio").hide();
    }
else
{
    delGraphMarker();

    
        loadMarker(map,"","");
}
    
}


function loadCitation(para,tg)
{
var flt="";
if (tg=="BIO" || tg=="NONBIO")
    flt=applyFilter();

var url ="http://"+location.hostname+"/visualization/searchcitation?search=" + para + "flag_search_citation" + tg +"&RID="+getURLParameter( 'RID' )+flt;

    $("#searchresultcitationtab").html('<div style="height: 100%; width: 100%; background: url(/images/loading/loading9.gif) 45% 50% no-repeat">  </div>');
    
                    $.post(url, {}, function(data) {
                              $("#searchresultcitationtab").html(data);
                });
    


}
function graphShowButton(flg)
{
    if(flg==true)
        {
        $("#toolsearchresult").show();}
    else
        {
    $("#toolsearchresult").hide();}
}

function showhidedetails()
{
    if (document.getElementById("hdSearchDetails").value=="0")
                    {
                        document.getElementById("hdSearchDetails").value="1";

                        $("#panel_detail").show();

                        if($("#panel").is(":visible")==false){
                            document.getElementById("GraphBio_Bar").style.width  = (document.documentElement.clientWidth-357) + "px";
                            document.getElementById("searchresultdetailtab").style.width  = (document.documentElement.clientWidth-415) + "px";
                            document.getElementById("searchresultcitationtab").style.width  = (document.documentElement.clientWidth-357) + "px";
                            
                            

                        }
                        else
                        {
                            document.getElementById("GraphBio_Bar").style.width  = (document.documentElement.clientWidth-30) + "px";
                            document.getElementById("searchresultdetailtab").style.width  = (document.documentElement.clientWidth-30) + "px";
                            document.getElementById("searchresultcitationtab").style.width  = (document.documentElement.clientWidth-30) + "px";
                          
                        }

                        document.getElementById("GraphBio_Bar").style.height  = (document.documentElement.clientHeight*20)/100 + "px";
                        document.getElementById("searchresultdetailtab").style.height  = (document.documentElement.clientHeight*10)/100 + "px";

//                        if (Flag_Search_Panel_Status=="BIO")
//                             searchaction("chkbio");
//                        if (Flag_Search_Panel_Status=="NONBIO")
//                             searchaction("chknonbio");



                    }
                else if (document.getElementById("hdSearchDetails").value=="1")
                    {
                        document.getElementById("hdSearchDetails").value="0";

                        $("#panel_detail").hide();


                    }
}
function loadgraph(selval)
{

                           if (Flag_Search_Panel_Status=="BIO" || Flag_Search_Panel_Status=="OVERLAY")
                                {if(selval==""){selval=getBioselection();}if(selval!="")SetBioChart(selval);}
                             else if (Flag_Search_Panel_Status=="NONBIO" || Flag_Search_Panel_Status=="OVERLAY")
                                 {if(selval==""){selval=getNonbioselection();}if(selval!="")SetNonBioChart(selval);}




                    
}



function searchResearch(researchid)
{
    if (researchid!="" && researchid>0)
        {
        
        
        
        var strReplaceAll = getURLParameter( 'ResearchTitle' );
var intIndexOfMatch = strReplaceAll.indexOf( "%20" );
 
// Loop over the string value replacing out each matching
// substring.
while (intIndexOfMatch != -1){
	// Relace out the current instance.
	strReplaceAll = strReplaceAll.replace( "%20", " " )
	 
	// Get the index of any next matching substring.
	intIndexOfMatch = strReplaceAll.indexOf( "%20" );
}
        
        
        document.getElementById("divTempl_ResearchTitle").innerHTML=strReplaceAll;

           
         $('#searchbox').attr("disabled", true);
         document.getElementById("searchbox").style.backgroundColor="#e1e2e2";

         
         $("#searchbox").val(researchid);

         if($("#searchbox").val()!="")
                                    {$("#divsearchfilter_bio").hide();
                $(".trigger").show();
                if($(".panel").is(":visible")==false){


                $(".panel").toggle();

                $(".trigger").toggleClass("active");
		}
                
                var cValue = $("#searchbox").val();
                $("#searchbox").val("");

                $.post("http://"+location.hostname+"/visualization/search", {RID: cValue+"flag_search_d_pg_t"+"ALL"}, function(data) {
                                $("#tdsearchresult").html(data);

                                setAccordion();


                              if(document.getElementById("accordion")){document.getElementById("accordion").style.height  = (document.documentElement.clientHeight-60) + "px";}
                              if(document.getElementById("divbiodata")){document.getElementById("divbiodata").style.height  = (document.documentElement.clientHeight-175) + "px";}
                              if(document.getElementById("divnonbiodata")){document.getElementById("divnonbiodata").style.height  = (document.documentElement.clientHeight-175) + "px";}
                              if(document.getElementById("divoverlaydata")){document.getElementById("divoverlaydata").style.height  = (document.documentElement.clientHeight-175) + "px";}
                             
                });

                                    }


        }
}


function startDownload()
{if (document.getElementById("chkdownloadagreement").checked==false)
        {
            alert("Please select the terms first to download the data");
            return;

        }
        
                            if (Flag_Search_Panel_Status=="BIO")
                                loadDetailgrid(getBioselection(),"BIO");
                            else if (Flag_Search_Panel_Status=="NONBIO")
                                loadDetailgrid(getNonbioselection(),"NONBIO");
                            else if (Flag_Search_Panel_Status=="OVERLAY")
                               loadDetailgrid(getOverlayselection(),"OVERLAY");
}
function setSearchFilter(str,tg)
{
var div
    if (tg=="BIO")
        {
    div=$("#divsearchfilter_bio");
    if (str=="")
    {div.html("");
       div.hide();
       return;
    }

    div.html('<div style="height: 100%; width: 100%; background: url(/images/loading/loading9.gif) 45% 50% no-repeat">  </div>');
    $.post("http://"+location.hostname+"/visualization/setsearchfilter", {search: str,tag:tg,RID:getURLParameter( 'RID' )}, function(data) {

                              div.html(data);

                             
                });

        }
        else if (tg=="NONBIO")
        {
    div=$("#divsearchfilter_nonbio");
    if (str=="")
    {div.html("");
       div.hide();return;
    }

    div.html('<div style="height: 100%; width: 100%; background: url(/images/loading/loading9.gif) 45% 50% no-repeat">  </div>');
    $.post("http://"+location.hostname+"/visualization/setsearchfilter", {search: str,tag:tg,RID:getURLParameter( 'RID' )}, function(data) {
                              div.html(data);
                              

                });

        }



}
function showhideFilter(Fstatus)
{  

    if (Flag_Search_Panel_Status=="BIO")
        {var para=getBioselection();
            if (Fstatus==true && para!="" && bioFilterWindow==true)
                {
                    $("#divsearchfilter_bio").show();
                    $("#divsearchfilter_nonbio").hide();
                }
            else if (Fstatus==false)
                {$("#divsearchfilter_bio").hide();}
            else
                $("#divsearchfilter_nonbio").hide();
        }
   else if (Flag_Search_Panel_Status=="NONBIO")
        {var para=getNonbioselection();
            if (Fstatus==true && para!="" && nonbioFilterWindow==true)
                {
                    $("#divsearchfilter_nonbio").show();

                    $("#divsearchfilter_bio").hide();
                }
            else if (Fstatus==false)
                $("#divsearchfilter_nonbio").hide();
            else
                $("#divsearchfilter_bio").hide();
        }


}



